/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 /***************************************************************************
 * Name: avp_demux.c
 *
 * Purpose: implementation demux for av player.
 *
 * Developer:
 *   wen.gu , 2022-01-18
 *
 * TODO:
 *
 ***************************************************************************/

 /******************************************************************************
 **    INCLUDES
 ******************************************************************************/
#include "avp_demux.h"
#include "avp_container.h"
#include "avp_mutex.h"
#include "avp_thread_worker.h"
#include "avp_log.h"
/******************************************************************************
 **    MACROS
 ******************************************************************************/
#define AVP_STREAM_INVALID_IDX (-99)
/******************************************************************************
 **    VARIABLE DEFINITIONS
 ******************************************************************************/

typedef struct _avp_selected_stream
{
    GS32 stream_index;
    avp_packet_queue_t output_queue;
}avp_selected_stream_t;

struct _avp_demux
{
    avp_container_t container;
    avp_thread_worker_t read_worker;
    avp_selected_stream_t selected_stream[AVP_MEDIA_CATERORY_MAX];
};

/******************************************************************************
 **    inner FUNCTION DEFINITIONS
 ******************************************************************************/

static GBOL avp_demux_stream_is_selected(avp_selected_stream_t* selected_streams, GS32 stream_idx)
{
    for (size_t i = 0; i < AVP_MEDIA_CATERORY_MAX; i++)
    {
        if (selected_streams[i].stream_index == stream_idx)
        {
            return GTRUE;
        }
    }

    return GFALSE;    
}

static avp_packet_queue_t avp_demux_get_output_queue(avp_demux_t demux, GS32 stream_idx)
{
    avp_selected_stream_t* selected_streams = demux->selected_stream;    
    for (size_t i = 0; i < AVP_MEDIA_CATERORY_MAX; i++)
    {
        if (selected_streams[i].stream_index == stream_idx)
        {
            return selected_streams[i].output_queue;
        }
    }

    return NULL;
}

static GBOL avp_demux_is_selected(avp_demux_t demux)
{
    avp_selected_stream_t* selected_streams = demux->selected_stream;
    for (size_t i = 0; i < AVP_MEDIA_CATERORY_MAX; i++)
    {
        if (selected_streams[i].stream_index != AVP_STREAM_INVALID_IDX)
        {
            return GTRUE;
        }
    }    

    return GFALSE;
}

static void avp_demux_selected_stream_init(avp_demux_t demux)
{
    avp_selected_stream_t* selected_streams = demux->selected_stream;
    for (size_t i = 0; i < AVP_MEDIA_CATERORY_MAX; i++)
    {
        selected_streams[i].stream_index = AVP_STREAM_INVALID_IDX;
        selected_streams[i].output_queue = NULL;
    }    
}


static void avp_demux_read_worker(avp_thread_worker_t worker, GPTR opaque)
{
    avp_demux_t demux = (avp_demux_t)opaque;
    avp_packet_t* pkt = NULL;
    avp_packet_queue_t output_queue = NULL;
    GErrc ret = G_OK;
    while (avp_thread_worker_running(worker))
    {
        if (!pkt)
        {
            ret = avp_container_ops_read(&demux->container, &pkt);

            if (G_OK == ret)
            {
                output_queue = avp_demux_get_output_queue(demux, pkt->stream_idx);
                ret = avp_packet_queue_put(output_queue, pkt);                
            }
        }

        if (G_OK == ret)
        {/** if success, just set NULL to read next packet */
            pkt = NULL;
        }
        else if (G_ErrOverflow == ret)
        { /** queue is full, then just wait a while */
            avp_thread_sleep(10); /** sleep 10ms, todo, could be use worker looper to instead ??  */
            ret = avp_packet_queue_put(output_queue, pkt);  
        }
        else if (G_ErrEOF == ret)
        {
            //todo something 
        }
        else
        {
            if (pkt)
            {
                avp_packet_destroy(pkt);
                pkt = NULL;
            }
        }        
    }
}

/******************************************************************************
 **    FUNCTION DEFINITIONS
 ******************************************************************************/

GErrc avp_demux_create(avp_demux_t* demux)
{
    avp_demux_t avpd = (avp_demux_t)malloc(sizeof(struct _avp_demux));

    if (!avpd)
    {
        LOGE("alloc avp demux instance failed\n");
        return G_ErrInsufficientResources;
    }

    GErrc ret = avp_thread_worker_create(avpd->read_worker, "demux read", avp_demux_read_worker, (GPTR)avpd);

    if (G_OK == ret)
    {
        LOGE("create demux read worker failed: %d\n", ret);
        free(avpd);
        return G_ErrInsufficientResources;
    }

    avp_demux_selected_stream_init(avpd);
    *demux = avpd;
    return G_OK;
}

void avp_demux_destroy(avp_demux_t demux)
{
    if (demux)
    {
        if (demux->read_worker)
        {
            avp_thread_join(demux->read_worker);
        }

        avp_container_ops_finish(&demux->container);
        free(demux);
    }
}

GErrc avp_demux_set_source(avp_demux_t demux, const GSTR url)
{
    if (!demux || !url)
    {
        return G_ErrBadParameter;
    }

    return avp_container_find(url, &demux->container);
}

GU32 avp_demux_stream_count(avp_demux_t demux)
{
    return demux ? avp_container_ops_stream_count(&demux->container) : 0;
}

GU32 avp_demux_stream_count_ex(avp_demux_t demux, avp_media_category_t category)
{
    return demux ? avp_container_ops_stream_count_ex(&demux->container, category) : 0;
}

GBOL avp_demux_stream_eixst(avp_demux_t demux, avp_media_category_t category)
{
    return avp_demux_stream_count_ex(demux, category) > 0; /** todo, is need set as GTRUE or GFALSE by hand */
}

GErrc avp_demux_stream_get_info(avp_demux_t demux, avp_media_category_t category, GU32 stream_index, avp_media_stream_t* stream_info)
{
    if (!demux || !stream_info)
    {
        return G_ErrBadParameter;
    }

    return avp_container_ops_stream_get_info(&demux->container, category, stream_index, stream_info);    
}

GErrc avp_demux_stream_select(avp_demux_t demux, GU32 stream_index, avp_packet_queue_t outque_queue) /***/
{
    if (!demux || !outque_queue)
    {
        return G_ErrBadParameter;
    }

    if (stream_index >= demux->stream_count)
    {
        return G_ErrOutOfRange;
    }

    GErrc ret = avp_container_ops_stream_select(&demux->container, stream_index);

    if (G_OK == ret)
    {
        avp_media_category_t category = avp_container_ops_stream_category(&demux->container, stream_index);
        demux->selected_stream[category].output_queue = outque_queue;
    }

    return ret;
}   

GErrc avp_demux_stream_unselect(avp_demux_t demux, GU32 stream_index)
{
    if (!demux)
    {
        return G_ErrBadParameter;
    }
    
    GErrc ret = avp_container_ops_stream_unselect(&demux->container, stream_index);

    if (G_OK == ret)
    {
        avp_media_category_t category = avp_container_ops_stream_category(&demux->container, stream_index);
        demux->selected_stream[category].pkt_queue = NULL;
        demux->selected_stream[category].stream_index = AVP_STREAM_INVALID_IDX;
    }

    return ret;
}

GErrc avp_demux_stream_unselect_all(avp_demux_t demux)
{
    if (!demux)
    {
        return G_ErrBadParameter;
    }

    avp_selected_stream_t* st = demux->selected_stream;
    for (size_t i = 0; i < AVP_MEDIA_CATERORY_MAX; i++)
    {
        if (st[i].stream_index != AVP_STREAM_INVALID_IDX)
        {
            GErrc ret = avp_container_ops_stream_unselect(&demux->container, st[i].stream_index);

            if (G_OK == ret)
            {
                st[i].stream_index = AVP_STREAM_INVALID_IDX;
                st[i].output_queue = NULL;
            }
            else
            {
                LOGE("unselect stream (idx:%d) failed\n", st[i].stream_index);
                //todo refine me. is need return
            }
        }
    }
    
    return G_OK;
}

GErrc avp_demux_stream_select_default(avp_demux_t demux, avp_media_category_t category, avp_packet_queue_t outque_queue)
{
    if (!demux || (category == AVP_MEDIA_CATEGORY_UNKNOWN) || (!outque_queue))
    {
        return G_ErrBadParameter;
    }

    GU32 stream_count = avp_demux_stream_count(demux);

    for (size_t i = 0; i < stream_count; i++)
    {
        if (category == avp_container_ops_stream_category(&demux->container, i))
        {
            demux->selected_stream[category].stream_index = i;
            demux->selected_stream[category].output_queue = outque_queue;
            return G_OK;
        }
    }
    
    return G_ErrUndefined;
}

GErrc avp_demux_stream_playing(avp_demux_t demux, avp_media_category_t category, GU32* stream_indexes)
{
    if (!demux || (category == AVP_MEDIA_CATEGORY_UNKNOWN))
    {
        return G_ErrBadParameter;
    }

    if (demux->selected_stream[category].stream_index != AVP_STREAM_INVALID_IDX)
    {
        *stream_indexes = demux->selected_stream[category].stream_index;
        return G_OK;
    }

    return G_ErrInvalidStatus;
}

GErrc avp_demux_start(avp_demux_t demux)
{
    if (demux)
    {

        return avp_thread_worker_start(demux->read_worker);
    }

    return G_ErrBadParameter;
}

GErrc avp_demux_pause(avp_demux_t demux)
{
    if (demux)
    {
        return avp_thread_worker_pause(demux->read_worker);
    }

    return G_ErrBadParameter;
}